package com.log4jviewer.ui.preferences.filters;

import org.eclipse.jface.bindings.keys.ParseException;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swtbot.eclipse.finder.SWTWorkbenchBot;
import org.junit.Test;

import utils.swtbot.UITestConstants;

/**
 * 
 * @author <a href="mailto:Daniil.Yaroslavtsev@gmail.com"> Daniil Yaroslavtsev </a>
 * 
 */
public class SettingsSavingTest extends AbstractFiltersPageTest {

    private static final String testString = "123321";

    protected static final SWTWorkbenchBot BOT = getBot();

    /**
     * Checks whether the parameters are survived by plugin when the settings window reopens.
     * 
     * @throws ParseException
     * */
    @Test
    public void testSettingsSavingByApplyBtnOnWindowRestart() throws ParseException {

        TableViewer filterTableViewer = getFilterSettings().getTableViewer();

        int filtersCount = 3;

        getFilterTable().setFocus();

        addFilters(filtersCount);

        int[] filtersRulesCounts = new int[filtersCount];

        for (int i = 0; i < filtersCount; i++) {
            filtersRulesCounts[i] = randomInt(1, 5);
            addFilterRules(i, filtersRulesCounts[i]);
        }

        writeToCell(filterTableViewer, 0, 0, testString, UITestConstants.F2_KEY_ACTIVATION);

        getAddFilterButton().setFocus();

        pressApply(); // apply changes
        closePreferencesDialog();

        openFiltersPreferencesPage(); // Open the "Filters" page   
        findAndParsePageControls(); // and parse it`s controls.

        boolean paramsSavedNormally = areParametersMatch(filtersRulesCounts);

        assertTrue(paramsSavedNormally);
    }

    public boolean areParametersMatch(final int[] filtersRulesCounts) {
        boolean result = true;

        int filterCount = filtersRulesCounts.length;

        if (filterCount == getFilterTable().rowCount()) {
            for (int i = 0; i < filterCount; i++) {
                getFilterTable().select(i);
                if (filtersRulesCounts[i] != getFilterRuleTable().rowCount()) {
                    result = false;
                    break;
                }
            }
        } else {
            result = false;
        }

        if (getFilterTable().cell(0, 0).equals(testString)) {
            // no code
        } else {
            result = false;
        }
        return result;
    }

}
